package com.xucan.equalsx;

public class ViolateHashCodeContract {
    private int value;

    public ViolateHashCodeContract(int value) {
        this.value = value;
    }

    // 重写 equals 方法，当两个对象的 value 属性相等时，认为它们相等
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        ViolateHashCodeContract other = (ViolateHashCodeContract) obj;
        return value == other.value;
    }

    // 重写 hashCode 方法，每次调用返回不同的值，违反了约定
    @Override
    public int hashCode() {
        return (int) (Math.random() * 100);
    }

    public static void main(String[] args) {
        ViolateHashCodeContract obj1 = new ViolateHashCodeContract(10);
        ViolateHashCodeContract obj2 = new ViolateHashCodeContract(10);

        // 检查 equals 方法
        boolean areEqual = obj1.equals(obj2);
        System.out.println("obj1 和 obj2 是否相等: " + areEqual);

        // 检查 hashCode 方法
        int hash1 = obj1.hashCode();
        int hash2 = obj2.hashCode();
        System.out.println("obj1 的 hashCode: " + hash1);
        System.out.println("obj2 的 hashCode: " + hash2);
        System.out.println("obj1 和 obj2 的 hashCode 是否相等: " + (hash1 == hash2));
    }
}